package cn.edu.buaa.treehole.controller.get;

import cn.edu.buaa.treehole.dao.exception.DaoException;
import cn.edu.buaa.treehole.dao.exception.PidNotExistException;
import cn.edu.buaa.treehole.service.PostListService;
import cn.edu.buaa.treehole.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping("/search")
public class SearchController {
    private final TagService tagService;
    private final PostListService postListService;

    @Autowired
    public SearchController(TagService tagService, PostListService postListService) {
        this.tagService = tagService;
        this.postListService = postListService;
    }

    @RequestMapping("tid")
    @ResponseBody
    public List<Long> searchTag(
            @RequestParam(value = "str") String str) {
        System.out.println(str);
        try {
            return tagService.getTidsByName(str);
        } catch (Exception e) {
            return new LinkedList<>();
        }
    }

    @RequestMapping("/tag_post")
    @ResponseBody
    public List<Long> tagPost(
            @RequestParam(value = "pt") long pt,
            @RequestParam(value = "num") int num,
            @RequestParam(value = "tid") long tid
    ) {
        try {
            return postListService.tagList(pt, num, tid);
        } catch (Exception e) {
            return new LinkedList<>();
        }
    }

    @RequestMapping("/str_tag_post")
    @ResponseBody
    public List<Long> strTagPost(
            @RequestParam(value = "str") String name
    ) {
        try {
            List<Long> tidList = tagService.getTidsByName(name);
            return postListService.totalList(new HashSet<>(tidList));
        } catch (Exception e) {
            return new LinkedList<>();
        }
    }

    @RequestMapping("/title_post")
    @ResponseBody
    public List<Long> titlePost(
            @RequestParam(value = "pt") long pt,
            @RequestParam(value = "num") int num,
            @RequestParam(value = "title") String title
    ) {
        try {
            return postListService.titleList(pt, num, title);
        } catch (Exception e) {
            return new LinkedList<>();
        }
    }
}
